class_name EntitySpawner extends Node2D


@export var entity_scene: PackedScene
var _current_spawn_interval: float = 1.5:
	set(value):
		_current_spawn_interval = clampf(value, end_interval, start_interval)
@export var start_interval: float = 1.5
@export var end_interval: float = 0.5
@export var time_delta: float = -0.01

@onready var _positions: Node2D = $Positions as Node2D
@onready var spawn_timer: Timer = $SpawnTimer as Timer
@onready var _multiplayer_spawner: MultiplayerSpawner = $MultiplayerSpawner as MultiplayerSpawner



func spawn_entity() -> void:
	var random_position: Marker2D = _positions.get_children().pick_random() as Marker2D
	var new_entity: Node2D = entity_scene.instantiate() as Node2D
	new_entity.position = random_position.position
	add_child(new_entity, true)
	_current_spawn_interval += time_delta
	restart_timer()
	

func _on_spwen_timer_timeout() -> void:
	spawn_entity()


func start_timer() -> void:
	if spawn_timer.is_stopped():
		spawn_timer.start(_current_spawn_interval)
	
	
func stop_timer() -> void:
	if not spawn_timer.is_stopped():
		spawn_timer.stop()


func restart_timer() -> void:
	if not spawn_timer.is_stopped():
		spawn_timer.stop()
	spawn_timer.start(_current_spawn_interval)


func _ready() -> void:
	_multiplayer_spawner.add_spawnable_scene(entity_scene.resource_path)
	_current_spawn_interval = start_interval
	if multiplayer.is_server():
		start_timer()
